package com.kuaimacode.kframework.api.controller.user;

import com.github.pagehelper.PageInfo;
import com.kuaimacode.kframework.api.controller.BaseController;
import com.kuaimacode.kframework.api.controller.pay.AlipayController;
import com.kuaimacode.kframework.api.controller.pay.WxpayController;
import com.kuaimacode.kframework.api.service.user.OrderEvaluateService;
import com.kuaimacode.kframework.api.service.user.OrderService;
import com.kuaimacode.kframework.api.vo.request.OrderEvaluateReq;
import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.component.ComponentUtil;
import com.kuaimacode.kframework.constants.PageConstants;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.mybatis.models.user.Order;
import com.kuaimacode.kframework.mybatis.models.user.OrderEvaluate;
import com.kuaimacode.kframework.util.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author 中元
 * @date 2019/04/08
 */
@RestController
@RequestMapping("/orderEvaluate")
@Api(tags = "订单评价",description = "订单评价相关api")
public class OrderEvaluateController extends BaseController {

    @Autowired
    private OrderEvaluateService orderEvaluateService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ComponentUtil componentUtil;
    @Autowired
    private AlipayController alipayController;
    @Autowired
    private WxpayController wxpayController;

    @ApiOperation(value = "查询评价列表", notes="查询评价列表")
    @GetMapping("/list")
    public JsonResult list( @RequestParam(value = "pageNum", required = true, defaultValue = PageConstants.PAGE_NUM+"") int pageNum,
                            @RequestParam(value = "pageSize", required = true, defaultValue = PageConstants.PAGE_SIZE+"") int pageSize){
        PageInfo<OrderEvaluate> list = orderEvaluateService.findAllByUserId(pageNum, pageSize, getUserId());
        return JsonResult.success(list);
    }

  /*  @ApiOperation(value = "编辑订单评价", notes="编辑订单评价")
    @PostMapping("/edit")
    @ApiImplicitParams({
        //@ApiImplicitParam(name = "id", value = "订单评价ID", required = true, dataType = "long",paramType = "path"),
        @ApiImplicitParam(name = "orderEvaluate", value = "OrderEvaluate实体", required = true, dataType = "OrderEvaluate")
    })
    public JsonResult edit(@RequestBody OrderEvaluate orderEvaluate, HttpServletRequest request){
        //orderEvaluate.setUserId(getUserId());
        if(orderEvaluateService.updateById(orderEvaluate)){
            return JsonResult.success();
        }else{
            return JsonResult.failure("操作失败");
        }
    }*/

    @ApiOperation(value = "新增订单评价", notes="新增订单评价，如果选择打赏金额，请后续调用对应的支付。/wxpay/reward、/alipay/reward-订单打赏支付参数生成")
    @PostMapping("/add")
    @ApiImplicitParam(name = "orderEvaluateReq", value = "订单评价实体", required = true, dataType = "OrderEvaluateReq")
    public JsonResult add(@Valid @RequestBody OrderEvaluateReq orderEvaluateReq, HttpServletRequest request){
        Order order = orderService.getById(orderEvaluateReq.getOrderId());
        Optional.ofNullable(order).orElseThrow(() -> new ServerInternalErrorException(ErrorEnum.ORDER_NOT_EXIST));
        List<OrderEvaluate> lists =  orderEvaluateService.findByOrderId(order.getId());
        if(lists.size() >0){
            throw new ServerInternalErrorException(ErrorEnum.ORDER_EVALUATE_HAS_EXIST);
        }
        Optional.of(order).filter(o->o.getStatus() == Constant.OrderStatusEnum.WAIT_EVLAUTE.getCode())
                .orElseThrow(() -> new ServerInternalErrorException(ErrorEnum.ORDER_STATUS_NOT_OK));
        OrderEvaluate orderEvaluate = new OrderEvaluate();
        BeanUtils.copyProperties(orderEvaluateReq, orderEvaluate);
        orderEvaluate.setId(null);
        orderEvaluate.setCreateAt(new Date());
        orderEvaluate.setRewardStatus(0);
        orderEvaluate.setMasterId(order.getMasterId());
        orderEvaluate.setUserId(getUserId());
        if(orderEvaluate.getReward() != null){
            //如果打赏金额不为空需要打赏
            String outTradeNo = CommonUtil.generateOrderNum(Constant.REWARD_OUT_TRADE_NO_PRE, orderEvaluate.getOrderId());
            orderEvaluate.setOutTradeNo(outTradeNo);
        }
        if(orderEvaluateService.save(orderEvaluate)){
            /*if(orderEvaluate.getReward() != null && orderEvaluate.getReward().compareTo(BigDecimal.ZERO)>0){
                //微信支付
                if(orderEvaluate.getPayType() == Constant.PayTypeEnum.WXPAY.getCode()){
                    return wxpayController.reward(orderEvaluate, request);
                }else{
                    //支付宝支付
                    return alipayController.reward(orderEvaluate);
                }
            }*/
            //修改订单状态为已完成
            order.setStatus(Constant.OrderStatusEnum.OK.getCode());
            order.setUpdateAt(new Date());
            orderService.updateById(order);
            return JsonResult.success();
        }else{
            return JsonResult.failure("操作失败");
        }
    }

    @ApiOperation(value = "根据Id删除订单评价", notes="根据Id删除订单评价")
    @GetMapping("/detete/{id}")
    @ApiImplicitParam(name = "id", value = "订单评价ID", required = true, dataType = "long",paramType = "path")
    public JsonResult delete(@PathVariable Long id, HttpServletRequest request){
        try {
            OrderEvaluate orderEvaluate = orderEvaluateService.getById(id);
            if (orderEvaluate == null || getUserId() != orderEvaluate.getUserId()){
                return JsonResult.failure("没有操作权限");
            }
            orderEvaluateService.removeById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure("操作失败");
        }
        return JsonResult.success();
    }

    @ApiOperation(value = "根据ID获取订单评价", notes="根据ID获取订单评价")
    @GetMapping("/getById/{id}")
    @ApiImplicitParam(name = "id", value = "订单评价ID", required = true, dataType = "long",paramType = "path")
    public JsonResult getById(@PathVariable Long id, HttpServletRequest request){
    	OrderEvaluate orderEvaluate = orderEvaluateService.getById(id);
        if (orderEvaluate == null || !getUserId().equals(orderEvaluate.getUserId())){
            return JsonResult.failure("没有操作权限");
        }
        //处理图片
        StringBuffer sb = new StringBuffer();
        Arrays.stream(Optional.ofNullable(orderEvaluate.getImages()).get().split(",")).forEach(o->{
            sb.append(componentUtil.convertImgUrl(o));
            sb.append(",");
        });
        String imgs = sb.toString().substring(0,sb.toString().length()-2);
        orderEvaluate.setImages(imgs);
        return JsonResult.success(orderEvaluate);
    }


}
